//tslint:disable
import { RecommendModalComponent } from 'src/app/coms/recommend-modal/recommend-modal.component';
import { Component, OnInit, Input, OnDestroy } from "@angular/core";

import { ActionSheetController, AlertController } from "@ionic/angular";
import { ModalController } from "@ionic/angular";

import { Subscription } from "rxjs";

import { MessageService } from "src/app/shared/service/message.service";

import { isNullOrUndefined } from 'util';

import { ActionSheetService, Modal, ModalService } from 'ng-zorro-antd-mobile';
import { EventService } from 'src/app/shared/service/event.service';
import { SharePageComponent } from 'src/app/coms/share-page/share-page.component';

import { RemarksContentComponent } from "../remarks-content/remarks-content.component";
import { ServiceModuleComponent } from '../service-module/service-module.component';
import { AppGlobalService } from "../../shared/service/app-global.service";
import { PageModalService } from "../../shared/service/page-modal-service";
import { HttpService } from "../../shared/service/http.service";
import { NewBusinessInfoModalComponent } from '../new-business-info-modal/new-business-info-modal.component';
import { ShareService } from 'src/app/shared/service/share.service';
import { ShareFormModalComponent } from "../share-form-modal/share-form-modal.component";
import { ImgSlidePage } from "../slides-imgage/img-slide.page";
import { ModalFromCenterLeave, ModalFromCenterEnter } from 'src/app/utils/transitions';
import { VideoImgPopupComponent } from '../video-img-popup/video-img-popup.component';
import { ifStmt } from '@angular/compiler/src/output/output_ast';
declare let $: any;
@Component({
  selector: "app-information-hall",
  templateUrl: "./information-hall.component.html",
  styleUrls: ["./information-hall.component.scss"]
})
export class InformationHallComponent implements OnInit, OnDestroy {
  @Input() tagData: any;
  @Input() noFilter: any;
  openInformation = false;
  openRemarks = false;
  icons = [];
  remarksText = "";
  remarksIcon: any;
  phoneArray = [];
  dataIndex: any;
  firstTextStyle: any = {};
  secondTagStyle: any = {};
  firstTagStyle: any = {};
  secondTestStyle: any = {};
  pageNo: any = 1;
  params: any;
  sessionId = localStorage.getItem("sessionId");
  // 声明订阅对象
  subscription: Subscription = null;
  emptyDataHint = "";
  showLoadMore = false;
  isshowContentRow = false;   // 判断展示还是隐藏
  pageSize: number;
  pageTotal: number;
  foldimgId = 'foldimgId';
  panelId = 'id-information-hall-panel';
  foldimg: any = "../../../assets/img/folddown.png";
  public refreshIds = new Set(); // 2024.10.16 refreshIds

  constructor(
    private appGlobalService: AppGlobalService,
    private actionSheetCtrl: ActionSheetController,
    private actionSheet: ActionSheetService, // 必须有
    private pageModalService: PageModalService, // 必须有
    private alertController: AlertController,
    private eventService: EventService,
    private message: MessageService,
    private httpService: HttpService,
    private shareService: ShareService,
    public modalController: ModalController
  ) {
    // 清除订阅
    this.eventService.eventEmit.on("clearInformationHallSubscription", (obj) => {
      const reqTag = localStorage.getItem('clearInformationHallSubscriptionTag');
      localStorage.removeItem('clearInformationHallSubscriptionTag');
      if (reqTag !== undefined) {
        try {
          console.log('msg----->clear ... ');
          this.subscription.unsubscribe();
        } catch (error) {
          console.log('error----->' + JSON.stringify(error));
        }
      }
    });
  }

  ngOnInit() {

    this.panelId += new Date().getTime();
    this.foldimgId += new Date().getTime();
    this.pageTotal = this.tagData.pageTotal;
    this.params = this.tagData.data.submit;
    this.pageSize = this.tagData.pageSize;

    const listenerName = this.tagData.name + 'AskForList';
    this.eventService.eventEmit.on(listenerName, (obj) => {
      this.refreshListData(obj);
    });
    this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize));
    if (this.tagData && this.tagData.hint) {
      this.emptyDataHint = this.tagData.hint;
    }

    if (!this.subscription && this.tagData.data.submit !== undefined && this.noFilter === undefined) {
      if (
        this.tagData.data.submit.content &&
        this.tagData.data.submit.content.showName
      ) {
        sessionStorage.setItem(
          "showName",
          this.tagData.data.submit.content.showName
        );
      } else {
        sessionStorage.removeItem("showName");
      }



      // // 自己添加demo数据
      // console.log('data list = ' + this.tagData.data.data);
      // const demoArray = this.tagData.data.data;

      // // tslint:disable-next-line:prefer-for-of
      // for (let index = 0; index < demoArray.length; index++) {
      //   const subject = demoArray[index];
      //   subject.shareRow = {
      //     data: [
      //       {
      //         shareIcon: "/assets/laijian/share_icon_qq@3x.png",
      //         imageUrl: "http://sz.pupuwang.com/img/logo.fa4183f9.png",
      //         label: "QQ",
      //         title: "罗湖区国贸123㎡餐馆转让",
      //         // tslint:disable-next-line:max-line-length
      //         webpageUrl: "https://m.laijian100.com/#/home/tab1/details?params=%7B%22plugin_id%22%3A%221%22%2C%22opportunity_id%22%3A%225ff7fca416fc3c00013e6b20%22%2C%22type%22%3A%22lj_opp%22%7D",
      //         content: "123平米，租金：元/月，23142323"
      //       }
      //       ,
      //       {
      //         shareIcon: "/assets/laijian/share_icon_WeChat@3x.png",
      //         imageUrl: "http://sz.pupuwang.com/img/logo.fa4183f9.png",
      //         label: "weixin",
      //         title: "罗湖区国贸123㎡餐馆转让",
      //         // tslint:disable-next-line:max-line-length
      //         webpageUrl: "https://m.laijian100.com/#/home/tab1/details?params=%7B%22plugin_id%22%3A%221%22%2C%22opportunity_id%22%3A%225ff7fca416fc3c00013e6b20%22%2C%22type%22%3A%22lj_opp%22%7D",
      //         content: "123平米，租金：元/月，23142323"
      //       },
      //       {
      //         shareIcon: "/assets/laijian/share_icon_douyin@3x.png",
      //         imageUrl: "http://sz.pupuwang.com/img/logo.fa4183f9.png",
      //         label: "douyin",
      //         title: "罗湖区国贸123㎡餐馆转让",
      //         // tslint:disable-next-line:max-line-length
      //         webpageUrl: "https://m.laijian100.com/#/home/tab1/details?params=%7B%22plugin_id%22%3A%221%22%2C%22opportunity_id%22%3A%225ff7fca416fc3c00013e6b20%22%2C%22type%22%3A%22lj_opp%22%7D",
      //         content: "123平米，租金：元/月，23142323"
      //       },
      //       {
      //         shareIcon: "/assets/laijian/share_icon_58@3x.png",
      //         imageUrl: "http://sz.pupuwang.com/img/logo.fa4183f9.png",
      //         label: "58",
      //         title: "罗湖区国贸123㎡餐馆转让",
      //         // tslint:disable-next-line:max-line-length
      //         webpageUrl: "https://m.laijian100.com/#/home/tab1/details?params=%7B%22plugin_id%22%3A%221%22%2C%22opportunity_id%22%3A%225ff7fca416fc3c00013e6b20%22%2C%22type%22%3A%22lj_opp%22%7D",
      //         content: "123平米，租金：元/月，23142323"
      //       }, {
      //         shareIcon: "/assets/laijian/share_icon_Wechat Moments@3x.png",
      //         imageUrl: "http://sz.pupuwang.com/img/logo.fa4183f9.png",
      //         label: "moment",
      //         title: "罗湖区国贸123㎡餐馆转让",
      //         // tslint:disable-next-line:max-line-length
      //         webpageUrl: "https://m.laijian100.com/#/home/tab1/details?params=%7B%22plugin_id%22%3A%221%22%2C%22opportunity_id%22%3A%225ff7fca416fc3c00013e6b20%22%2C%22type%22%3A%22lj_opp%22%7D",
      //         content: "123平米，租金：元/月，23142323"
      //       },
      //       {
      //         shareIcon: "/assets/laijian/share_icon_save_pictures@3x.png",
      //         imageUrl: "http://sz.pupuwang.com/img/logo.fa4183f9.png",
      //         label: "savePic",
      //         title: "罗湖区国贸123㎡餐馆转让",
      //         // tslint:disable-next-line:max-line-length
      //         webpageUrl: "https://m.laijian100.com/#/home/tab1/details?params=%7B%22plugin_id%22%3A%221%22%2C%22opportunity_id%22%3A%225ff7fca416fc3c00013e6b20%22%2C%22type%22%3A%22lj_opp%22%7D",
      //         content: "123平米，租金：元/月，23142323"
      //       }
      //     ],
      //     maxIcon: "5",
      //     iconList: {
      //       shareBtn: {
      //         iconName: "../../../assets/img/list_share@3x.png",
      //         fieldLinkType: {
      //           link: {
      //             type: "page",
      //             params: {
      //               plugin_id: "1",
      //               opportunity_id: "5ff7fca416fc3c00013e6b20"
      //             },
      //             target: 206213
      //           }
      //         },
      //         modelType: "iconLink",
      //         label: "分享"
      //       }
      //     }
      //   };
      //   this.tagData.data.data[index] = subject;
      // }
      // event.target.disabled = true;
      this.message.clearMessage();
      // 获取筛选参数
      this.subscription = this.message.getMessage().subscribe(param => {

        if (param === undefined) {
          return;
        } else if (param.type === 'ionRefresh') {
          this.refreshData(param);
          return;
        }
        this.pageNo = 1;
        this.params.sessionId = localStorage.getItem("sessionId");
        // 参数
        this.params.content = param;
        // 页面数据参数
        this.params.content.pageNo = this.pageNo;
        // 请求获取新数据
        this.httpService.post(
          "application/submit",
          this.params,
          res => {
            console.log("submit");
            // 请求数据成功
            if (res.success) {
              this.pageTotal = res.data.submit.content.pageTotal;

              // tslint:disable-next-line:max-line-length
              this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal > this.pageSize && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) && this.tagData.asyncShow !== 'true';

              const result = res.data.data;
              // 筛选数据
              this.tagData.data.data = result;
              // 自动回到顶部
              setTimeout(() => {
                const el = document.getElementById('information0');
                if (el) {
                  el.scrollIntoView(true);
                }

              }, 200);
            } else {
              // 请求数据失败
              this.appGlobalService.showToast(res.message, 2000, "middle");
            }
          },
          err => {
            // 请求数据失败
            this.appGlobalService.showToast(err.message, 2000, "middle");
          }
        );
      });
    }







  }

  refreshListData(param) {
    const that = this;
    if (param === undefined) {
      return;
    }
    this.pageNo = 1;
    if (!param.showName) {
      if (this.tagData.data.moreButton && this.tagData.data.moreButton.link.params.showName) {
        param.showName = this.tagData.data.moreButton.link.params.showName;
      } else if (this.tagData.data.submit && this.tagData.data.submit.content.showName) {
        param.showName = this.tagData.data.submit.content.showName;
      }
    }
    that.params.content = param;
    that.params.content.pageNo = this.pageNo;
    that.params.sessionId = localStorage.getItem('sessionId');
    this.httpService.post('application/submit', that.params, res => {
      if (res.success) {
        this.tagData.data.data = [];
        // const result = res.data.data; // JSON.parse(res.data.data);
        // this.listData = res.data.data;
        if (res.data.submit) {
          this.params = res.data.submit; // 为了每次刷新下一页的参数 "oldIndex"
        }

        this.tagData.data.data = res.data.data;

        if (res.data.moreButton) {
          this.tagData.data.moreButton = res.data.moreButton;
        }
        this.pageTotal = this.tagData.pageTotal;

        // tslint:disable-next-line:max-line-length
        this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) && this.tagData.asyncShow !== 'true';
      } else {
        // 请求数据失败
        this.tagData.data.data = [];
        this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    },
      err => {
        // 请求数据失败
        this.tagData.data.data = [];
        this.appGlobalService.showToast(err.message, 2000, 'middle');
      });
  }

  /**
   *
   * @param item 打开图标
   */
  openIcon(item, dataIndex?, maxIconList?) {
    if (maxIconList && maxIconList === '2') {
      this.icons = item.slice(1);
    } else {
      this.icons = item.slice(2);
    }

    this.showActionSheet(this.icons);
    // this.openInformation = true;
    this.dataIndex = dataIndex;
  }

  /**
   * 关闭图标
   */
  hiddenInformation() {
    this.openInformation = false;
    this.openRemarks = false;
  }

  // 分享弹框
  async presentShareModal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }


  // 分享弹框
  async presentShare58Modal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'recommend-modal',
      backdropDismiss: true,
      component: ShareFormModalComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }
  updateItem() {

    const that = this;

    if (!this.tagData.data.data[that.dataIndex].id) {
      return;
    }
    if (that.tagData.data.data[that.dataIndex].updateItemType !== undefined
      && that.tagData.data.data[that.dataIndex].updateItemType === 'delete') {
      that.tagData.data.data.splice(that.dataIndex, 1);
      return;
    }
    let page: any = this.appGlobalService.getCurrentTarget() ? this.appGlobalService.getCurrentTarget() : {};
    if (page && page.params) {
    } else {
      page.params = {}
    }
    page.params.id = this.tagData.data.data[that.dataIndex].id;

    if (this.tagData.data.data[that.dataIndex].viewId !== undefined
      && this.tagData.data.data[that.dataIndex].viewId !== '0') {
      page.params['opportunity_opportunity_id'] = this.tagData.data.data[that.dataIndex].id;
      page['viewId'] = this.tagData.data.data[that.dataIndex].viewId;
      page['sessionId'] = localStorage.getItem('sessionId')
      this.httpService.post('application/part', page, async resData => {
        const tagData = JSON.parse(resData.script).tags;
        if (tagData) {
          tagData.forEach(element => {
            if (element.style.includes('appInfoListTag') && element.data && element.data.data[0]) {
              that.tagData.data.data.splice(that.dataIndex, 1, element.data.data[0]);
            }
          });
        }
      });
    } else {
      this.httpService.post('application/page', page, async res => {
        const tagData = JSON.parse(res.script).views[0].tags;
        tagData.forEach(element => {
          if (element.style === 'appInfoListTag' && element.data && element.data.data[0]) {
            that.tagData.data.data.splice(that.dataIndex, 1, element.data.data[0]);
          }

        });
      });
    }

  }
  /**
   *
   * @param item 点击图标
   */
  iconClick(item, dataIndex?) {
    if (dataIndex >= 0) {
      this.dataIndex = dataIndex;
    }
    this.hiddenInformation();
    // console.log(item);
    if (item.modelType === "pageModal") {
      this.pageModalService.openPage(item.link, '', res => {
        if (res) {
          this.updateItem();
        }
      });
    }
    else if (item.modelType === "iconLink") {
      if (item.link.type && item.link.type === 'chat') {//

        if (item.button !== undefined && item.button.submit !== undefined) {
          item.beforeSubmit = item.button.submit;
        }
        if (item.beforeSubmit) {
          const params = {
            content: item.beforeSubmit.content,
            id: item.beforeSubmit.id,
            sessionId: localStorage.getItem("sessionId")
          };
          this.httpService.post("application/submit", params, res => {
            if (res.success) {
              if (res.data && res.data.eventResult && item.link.params && item.link.params.eventResult) {
                item.link.params[item.link.params.eventResult] = res.data.eventResult;
              }
              this.httpService.gotoChat(item, item.link.params.customerUserId);
            } else {
              if (res.message && res.message.length > 0)
                this.appGlobalService.showToast(res.message, 1500, "middle");
            }
          });
        } else {
          this.httpService.gotoChat(item, item.link.params.customerUserId);
        }

      } else if (item.label === '分享') {
        const params = {
          sessionId: localStorage.getItem("sessionId"),
          pageId: item.link.target,
          params: item.link.params
        };
        this.httpService.post('application/page', params, res => {
          console.log(JSON.parse(res.script));
          const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
          // console.log(tmpShareData);
          this.presentShareModal(tmpShareData);
        });

      } else if (item.action && item.action === 'submitlink') {
        let tempSubmit;
        if (item.button && item.button.submit) {
          tempSubmit = item.button.submit;
        }
        const params = {
          content: tempSubmit.content,
          id: tempSubmit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
          if (res.success) {
            if (res.data && res.params.eventReturnParam) {
              item.link.params[res.params.eventReturnParam] = res.params[res.params.eventReturnParam];
            }
            if (res.data && res.params.eventResult) {
              item.link.params[res.params.eventResult] = res.data.eventResult;
            }
            this.pageModalService.openPage(item.link);
          } else {
            if (res.message && res.message.length > 0)
              this.appGlobalService.showToast(res.message, 1500, "middle");
          }
        });
      } else {
        this.pageModalService.openPage(item.link);
      }
    }
    else if (item.modelType === "iconSubmit") {
      let submit;
      if (item.button && item.button.submit) {
        submit = item.button.submit;
      } else if (item.submit) {
        submit = item.submit;
      }
      const params = {
        content: submit.content,
        id: submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (submit.content !== undefined && submit.content.btnId !== undefined) {
            const btnId = submit.content.btnId;
            $('#' + btnId).click();
          } else {
            // const tabIndex = parseInt(item.tabClick);
            // if (item.tabClick) {
            //   setTimeout(() => {
            //     this.eventService.eventEmit.emit("topTabChangeByIndex", tabIndex);
            //   }, 1000);
            // }
            if (item.refresh !== undefined) {
              this.appGlobalService.reloadCurrentPage();
            }
            if (item.link && item.link.target) {
              const pageParams = {
                pageId: item.link.target,
                params: item.link.params ? item.link.params : {},
                sessionId: localStorage.getItem("sessionId")
              };
              this.appGlobalService.goToForward(pageParams);
            }
          }

        }
      });
    }
    else if (item.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    }
    else if (item.modelType === "phone") {
      // 电话
      this.phoneArray = item.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), item.label);
      }
    }
    else if (item.modelType === "dialog") {
      // 备注
      // this.remarksIcon = item;
      // this.openRemarks = true;
      this.presentModal("remarks", item);
    }
    // 商铺列表新增类型
    else if (item.modelType === 'pageDialog') {
      this.openTipsPageModal("recommend-modal", item);
    }
    // 新增两个components类型
    else if (item.modelType === "remarkList") {
      // tslint:disable-next-line:max-line-length
      // const moreObj = JSON.parse('{"layout":"right","data":[{"submit":{"id":"refresh","content":{"opportunity_id":"5eb3aed42872fb0001f76ed7"}},"action":"submit","label":"刷新","paramName":"opportunity_id"},{"link":{"type":"page","params":{"opportunity_id":"5eb3aed42872fb0001f76ed7"},"target":144348},"action":"link","label":"修改"}],"icon":"nav_icon_more@3x.png"}');
      if (item.listRemark) {
        this.remarkList(item);
      }
    }
    else if (item.modelType === "serviceModal") {
      this.openSeviceModal("sevice-modal", item);
    }
    if (item.modelType === "childIconLink") {
      if (item.childIconList) {
        this.remarkList(item);
      }
    }
    // 1.7.0 新增弹窗
    else if (item.modelType === 'question') {
      this.presentQuestion(item, item.msg, dataIndex);
    }
    // 1.6.21 复制按钮
    else if (item.modelType === 'copy') {
      this.shareService.copyUrl(item.msg);
    }
  }
  async openSeviceModal(className, item) {
    const type = {
      "sevice-modal": ServiceModuleComponent,
    };
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: className,
      component: type[className],
      componentProps: { tagData: item }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }

  remarkList(more, dataIndex?) {
    const that = this;
    const buttons: any = [];
    if (more.childIconList) {
      more.listRemark = more.childIconList;
    } else if (more.iconList) {
      more.listRemark = more.iconList;
    } else {
      more['listRemark'] = more;
    }
    more.listRemark.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          // console.log(more.listRemark[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.selectItem(more, buttonIndex, undefined, dataIndex);
          }, 200);
        }
      }
    );
  }

  remarkList2(more, item, dataIndex?) {
    const that = this;
    const buttons: any = [];
    if (more.childIconList) {
      more.listRemark = more.childIconList;
    } else if (more.iconList) {
      more.listRemark = more.iconList;
    } else {
      more['listRemark'] = more;
    }
    more.listRemark.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          // console.log(more.listRemark[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.selectItem(more, buttonIndex, item, dataIndex);
          }, 200);
        }
      }
    );
  }

  selectItem(item, index, currentItem, dataIndex?) {
    console.log('msg-----?', currentItem);
    const itemObj = item.listRemark[index];
    if (itemObj.modelType === 'dialog') {
      if (currentItem
        && currentItem.remarkButtons
        && currentItem.remarkButtons.iconList
        && currentItem.remarkButtons.iconList[0]) {
        const firstDialogBtn = currentItem.remarkButtons.iconList[0];
        if (itemObj.matchKey === firstDialogBtn.matchKey) {
          itemObj['formData'] = firstDialogBtn.formData;
        }
      }
      this.presentModal("remarks", itemObj);
    } else if (itemObj.modelType === 'pageDialog') {
      this.openTipsPageModal("recommend-modal", itemObj);
    } else if (itemObj.modelType === 'iconLink') {
      // 修改 领取类型按钮
      this.pageModalService.openPage(itemObj.link);

    } else if (itemObj.modelType === 'phone') {
      // 电话
      this.phoneArray = itemObj.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), itemObj.label);
      }
    } else if (itemObj.modelType === 'iconSubmit') {
      let submit;
      if (itemObj.button && itemObj.button.submit) {
        submit = itemObj.button.submit;
      } else if (itemObj.submit) {
        submit = itemObj.submit;
      }
      // 领取
      const params = {
        content: submit.content,
        id: submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (itemObj.refresh !== undefined) {
            this.appGlobalService.reloadCurrentPage();
          }
          if (itemObj.link && itemObj.link.target) {
            if (res.data && res.data.eventResult && itemObj.link.params && itemObj.link.params.eventResult) {
              if (res.data.eventResult) {
                itemObj.link.params[itemObj.link.params.eventResult] = res.data.eventResult;
              } else if (res.data.eventReturnParam) {
                itemObj.link.params[itemObj.link.params.eventResult] = res.data.eventReturnParam;
              } else {
                itemObj.link.params[itemObj.link.params.eventResult] = res.eventResult;
              }
            }
            this.pageModalService.openPage(itemObj.link);


          }
        }
      });
    } else if (itemObj.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: itemObj.submit.content,
        id: itemObj.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    } else if (itemObj.modelType === 'question') { // 1.7.0 add
      this.presentQuestion(itemObj, itemObj.msg, dataIndex);
    } else if (itemObj.modelType === 'remarkList') {
      if (currentItem.addRemarksList) {
        this.remarkList(currentItem.addRemarksList);
      }
    }
  }


  showActionSheet(icons) {
    const that = this;
    const buttons: any = [];
    icons.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          console.log(icons[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.iconClick(icons[buttonIndex]);
          }, 200);
        }
      }
    );
  }

  async presentModal(value, item) {
    console.log("item", item);
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: value,
      component: RemarksContentComponent,
      componentProps: { item, type: value }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData, "moddddddd");
  }

  async presentAction() {
    const buttonsArr = [
      {
        text: "取消",
        cssClass: ["action-sheet-font-color", "action-sheet-font-top"],
        handler: () => {
          actionSheet.dismiss();
        }
      }
    ];
    if (this.phoneArray[1]) {
      buttonsArr.unshift({
        text: this.phoneArray[1],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(Number(this.phoneArray[1]));
        }
      });
    }

    if (this.phoneArray[0]) {
      buttonsArr.unshift({
        text: this.phoneArray[0],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(this.phoneArray[0]);
        }
      });
    }

    const actionSheet = await this.actionSheetCtrl.create({
      mode: "md",
      cssClass: "match-padding",
      buttons: buttonsArr
    });
    await actionSheet.present();
  }

  async presentAlertConfirm(mobile, name?) {
    const msg = (name ? name + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });

    await alert.present();
  }


  async presentQuestion(itemObj, msg, dataIndex) {

    const alert = await this.alertController.create({
      header: '',
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "确定",
          handler: () => {
            let submitParam;
            if (itemObj.submit) {
              submitParam = itemObj.submit;
            } else if (itemObj.button) {
              submitParam = itemObj.button.submit;
            }
            const params = {
              content: submitParam.content,
              id: submitParam.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              this.appGlobalService.showToast(res.message, 1500, "middle");
              if (res.success) {
                if (itemObj.refresh !== undefined) {
                  this.appGlobalService.reloadCurrentPage();
                } else {
                  if (dataIndex >= 0 && dataIndex < this.tagData.data.data.length) {
                    this.tagData.data.data.splice(dataIndex, 1);
                  }
                  if (this.tagData.data.data.length === 0) {
                    //1.7.0 新增
                    this.tagData.data.moreButton = {};
                  }
                }
              }
            });
          }
        }
      ]
    });

    await alert.present();
  }

  /**
   * 提交备注
   */
  submitRemarks() {
    if (this.remarksText === "") {
      this.appGlobalService.showToast("请填写备注", 1000, "top");
      return;
    }
    const contentArray = this.remarksIcon.formData.button.submit.content;
    // tslint:disable-next-line:no-string-literal
    contentArray["remark_text"] = this.remarksText;
    const params = {
      content: contentArray,
      id: this.remarksIcon.formData.button.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      if (res.success) {
        this.remarksText = "";
        this.openRemarks = false;
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      } else {
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      }
    });
  }

  go(item) {
    if (this.tagData.name === 'appInfoListTag-huifu') {
      this.eventService.eventEmit.emit("selectBank", { code: item.code, name: item.title });
      this.appGlobalService.goBack();
    } else
      if (item.link) {
        item.link.modalCss = 'video-modal';
        this.pageModalService.openPage(item.link);
      }
  }

  pullToRefresh() {

  }
  refreshData(event?) {
    this.params.sessionId = localStorage.getItem("sessionId");
    // 请求下一个页面
    this.pageNo = 1;
    this.params.content.pageNo = this.pageNo;
    // 请求获取新数据
    this.httpService.post("application/submit", this.params, res => {
      // 请求数据成功
      if (res.success) {

        if (Array.isArray(res.data.data) && res.data.data.length > 0) {
          this.tagData.data.data = res.data.data;

          // this.params = res.data.submit;
        } else {
          this.tagData.data.data = [];
          // 没有数据了
          // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
        }
        if (event) {
          event.target.complete();
        }

      } else {
        // 请求失败，更新当前页数
        this.tagData.data.data = [];
        this.pageNo = 1;
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, "middle");
        if (event) {
          event.target.complete();
        }
      }
    });
  }

  loadData(event) {
    setTimeout(() => {
      this.params.sessionId = localStorage.getItem("sessionId");
      // 请求下一个页面
      this.pageNo = this.pageNo + 1;
      this.params.content.pageNo = this.pageNo;
      // 请求获取新数据
      this.httpService.post("application/submit", this.params, res => {
        // 请求数据成功
        if (res.success) {
          // 追加返回数据
          if (Array.isArray(res.data.data) && res.data.data.length > 0) {
            // 追加数据
            res.data.data.map(item => {
              this.tagData.data.data.push(item);
            });
            // this.params = res.data.submit;
          } else {
            // 没有数据了
            // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
          }
          event.target.complete();
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
          event.target.complete();
        }
      });
    }, 500);
  }

  openModalLink(item, label) {
    try {
      if (label === '业务中' || label === '签约中') {
        if (item && item.type === 'modal') {
          this.openNewBusinessInfoModal("recommend-modal", item);
        }
      } else {
        return;
      }

    } catch (error) {
    }
  }

  async openNewBusinessInfoModal(className, item: any) {
    try {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.target,
        params: item.params
      };
      this.httpService.post('application/page', params, async res => {
        const tagData = JSON.parse(res.script).views[0].tags[0].data;
        if (tagData.data && tagData.data.length > 0) {
          const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: className,
            animated: false,
            component: NewBusinessInfoModalComponent,
            componentProps: { tagData }
          });
          await modal.present();
          // 监听销毁的事件
          const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
        }
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }

  }

  async openTipsPageModal(className, item: any) {
    try {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params
      };
      this.httpService.post('application/page', params, async res => {
        const tagData = JSON.parse(res.script).views[0].tags[0].data;
        if (tagData) {
          const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: className,
            animated: false,
            component: RecommendModalComponent,
            componentProps: { tagData },
            leaveAnimation: ModalFromCenterLeave,
            enterAnimation: ModalFromCenterEnter
          });
          await modal.present();
          const modalData = await modal.onDidDismiss().then((data) => {
            this.appGlobalService.reloadCurrentPage();
          }); // 获取关闭传回的值
        }
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }



  // async openTipsPageModal(className, item: any) {
  //   try {
  //     const params = {
  //       sessionId: localStorage.getItem("sessionId"),
  //       pageId: item.target,
  //       params: item.params
  //     };
  //     this.httpService.post('application/page', params, async res => {
  //       const tagData = JSON.parse(res.script).views[0].tags[0].data;
  //       if (tagData.data && tagData.data.length > 0) {
  //         const modal = await this.modalController.create({
  //           showBackdrop: true,
  //           cssClass: className,
  //           animated: false,
  //           component: RecommendModalComponent,
  //           componentProps: { tagData }
  //         });
  //         await modal.present();
  //         // 监听销毁的事件
  //         const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  //       }
  //     });
  //   } catch (error) {
  //     console.log('error----->' + JSON.stringify(error));
  //   }
  // }

  gotoSharePage(obj) {
    if (obj.action && obj.action === 'link') {
      this.appGlobalService.openPage(obj.fieldLinkType.link);
      return;
    }

    // 1.6.22 新增提交链接
    if (obj.action && obj.action === 'submitlink') {
      if (obj.fieldSubmitType && obj.fieldSubmitType.submit) {

        const params = {
          content: obj.fieldSubmitType.submit.content,
          id: obj.fieldSubmitType.submit.id,
          sessionId: localStorage.getItem('sessionId')
        };
        // 请求获取新数据
        this.httpService.post('application/submit', params, res => {
          // 请求数据成功
          if (res.success) {
            if (res.params.eventReturnParam) {
              obj.fieldLinkType.link.params[res.params.eventReturnParam] = res.params[res.params.eventReturnParam];
            }
            this.pageModalService.openPage(obj.fieldLinkType.link);
          } else {
            // 请求数据失败
            this.appGlobalService.showToast(res.message, 2000, 'middle');
          }
        },
          err => {
            // 请求数据失败
            this.appGlobalService.showToast(err.message, 2000, 'middle');
          });
      }
      return;
    }


    if (obj.tips) {
      this.appGlobalService.showToast(obj.tips, 2000, "middle");
      return;
    }
    if (obj && obj.label) {
      switch (obj.label) {
        case 'qq':
          this.shareService.shareQQ(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'qzone':
          this.shareService.shareQQZone(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'wechat':
          this.shareService.shareWeiXin(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'moment':
          this.shareService.shareMoments(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case '58':
          this.shareService.share58(obj);
          break;
        case 'tikTok': // 抖音
          if (obj.isInValidImgPosterSharing) {
            // 脚本配置 <dataItem name="isInValidImgPosterSharing" value="true"/>
            // 用于新增需求 求租求购，找店、找写字楼、找厂房等：没有图片或信息本身任何图片，生成画报，分享画报图片
            this.shareService.shareDouyinForInValidImg(obj.link.fieldLinkType);
          } else {
            this.shareService.shareDouyin(obj.title, obj.content, obj.imageUrls, obj.webpageUrl, obj.shareType);
          }
          break;
        case 'kwai': // 快手 https://play.google.com/store/apps/details?id=com.kwai.video&hl=zh&gl=US
          this.shareService.shareKuaishou(obj.title, obj.content, obj.imageUrl, obj.webpageUrl, obj.shareType);
          break;
        case 'copy':
          this.shareService.copyUrl(obj.webpageUrl);
          break;
        case 'savePic':
          // this.shareService.savePic();
          break;
        case 'posterSharing':
          this.shareService.posterSharing(obj.link.fieldLinkType);
          break;
        default:
          console.log('...gotoSharePage');
          break;
      }

    }
  }

  openShareModal(obj) {
    if (obj) {
      let subject = obj;
      if (obj.shareBtn && obj.shareBtn.fieldLinkType) {
        subject = obj.shareBtn.fieldLinkType;
      }
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: subject.link.target,
        params: subject.link.params
      };
      this.httpService.post('application/page', params, res => {
        console.log(JSON.parse(res.script));
        const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
        this.presentShareModal(tmpShareData);
      });
    }
  }

  async previewImage(imageUrl, tmpIndex, isPreview) {
    if (isPreview && isPreview !== undefined) {
      // const that = this;
      let tempImageUrl = 'assets/img/default_img.png';
      if (imageUrl !== undefined) {
        tempImageUrl = imageUrl;
      }
      const value = { img: [tempImageUrl], index: tmpIndex };
      const modal = await this.modalController.create({
        component: ImgSlidePage,
        componentProps: { value: JSON.stringify(value) }
      });
      return await modal.present();
    }

  }


  async previewVideo(url, isPreview) {
    if (url && isPreview && isPreview !== undefined) {
      let data = [];
      data['videoUrl'] = [url];
      const modal = await this.modalController.create({
        component: VideoImgPopupComponent,
        componentProps: { tagData: data }
      });
      return await modal.present();
    }
  }

  showclick(e, index) {
    e.stopPropagation();
    this.isshowContentRow = !this.isshowContentRow;
    const foldId = "#" + this.foldimgId + index;
    const mPanelId = "#" + this.panelId + index;
    if ($(foldId).attr('src') === '../../../assets/img/folddown.png') {
      $(foldId).attr("src", "../../../assets/img/foldup.png");
      $(mPanelId).slideToggle("slow");
    } else {
      $(foldId).attr("src", "../../../assets/img/folddown.png");
      $(mPanelId).slideToggle("slow");
    }
  }


  ngOnDestroy(): void {
    this.eventService.removeCustomListListenersByName(this.tagData.name + 'AskForList');
    if (this.tagData && this.refreshIds) {
      this.refreshIds.forEach(element => {
        this.eventService.removeCustomListListenersByName(element);
      });
    }
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
  moreClick(link, item?) {
    if (item !== undefined) {
      if (item.button !== undefined
        && item.button.submit !== undefined) {
        const tempSubmit = item.button.submit;
        const params = {
          content: tempSubmit.content,
          id: tempSubmit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
          if (res.success) {
            if (res.data && res.data.eventResult && item.link.params && item.link.params.eventResult) {
              item.link.params[item.link.params.eventResult] = res.data.eventResult;
            }
            this.pageModalService.openPage(link);
          } else {
            if (res.message && res.message.length > 0)
              this.appGlobalService.showToast(res.message, 1500, "middle");
          }
        });
      } else {
        this.pageModalService.openPage(link);
      }
    } else {
      this.pageModalService.openPage(link);
    }
  }

  imgClick(index, arrays) {
    this.pageModalService.openImage_url(index, arrays);
  }

  topRightClick(newLinkBtn, e) {
    e.stopPropagation();
    if (newLinkBtn !== undefined && newLinkBtn[0]) {
      this.iconClick(newLinkBtn[0]);
    }
  }

  topLeftClick(newLinkBtn, label, e) {
    e.stopPropagation();
    if (newLinkBtn !== undefined && newLinkBtn[0]) {
      this.openModalLink(newLinkBtn[0].link, label);
    }
  }


  ngAfterViewInit(): void {
    let that = this;
    // 2023.12.08 是否存在刷新控件
    if (that.tagData
      && that.tagData.data
      && that.tagData.data.data
      && that.tagData.data.data.length > 0) {
      // 2023.12.08 配置了某个属性才检查是否有下拉刷新事件
      if (that.tagData.data.data[0].isShowRefresher === 'true') {
        const debouncedHandler = that.appGlobalService.debounce((data: any) => {
          if (that.tagData.refreshId !== undefined) {
            that.eventService.eventEmit.emit(that.tagData.refreshId, '1');
          }
        }, 300);
        that.eventService.eventEmit.on('checkListIsShowRefresher', debouncedHandler);
        if (that.tagData.refreshId !== undefined) {
          that.tagData.refreshId += 'a';
          that.refreshIds.add(that.tagData.refreshId);
          console.log('init list name success!', that.tagData.refreshId);
          const debouncedHandler2 = that.appGlobalService.debounce((data: any) => {
            let tempRefresher = true;
            if (tempRefresher) {
              tempRefresher = false;
              let tempParamsContent = {};
              if (!that.params) {
                that.params = { content: {} };
                if (that.tagData.data.submit.content) {
                  that.params.content = that.tagData.data.submit.content;
                }
              } else {
                if (that.params && that.params.content) {
                  tempParamsContent = JSON.parse(JSON.stringify(that.params.content));
                }
              }
              that.refreshListData(tempParamsContent);
              setTimeout(() => {
                tempRefresher = true; //防止2秒内重复请求
              }, 2000);
            }
          },300);
          that.eventService.eventEmit.on(that.tagData.refreshId, debouncedHandler2);
        }
      }
    }
  }
}




